<template>
    <div class="auditor-page-container">
        <el-card v-if="!isLoggedIn" class="login-card">
            <template #header>
                <div class="card-header">
                    <span>审核员登录</span>
                </div>
            </template>
            <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" @submit.prevent="verifyPassword">
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="loginForm.password" show-password autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="verifyPassword" :loading="loginLoading" class="login-button">登录</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card v-else class="auditor-panel">
            <template #header>
                <div class="card-header">
                    <span>待审核学分认证</span>
                </div>
            </template>
            
            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="通用认证" name="general">
                    <el-table :data="pendingCertifications" style="width: 100%" v-loading="loadingGeneral" border stripe>
                        <el-table-column prop="id" label="申请ID" width="180"></el-table-column>
                        <el-table-column prop="applicantUsername" label="申请人"></el-table-column>
                        <el-table-column prop="description" label="认证描述" show-overflow-tooltip></el-table-column>
                        <el-table-column label="证明图片" width="120">
                            <template #default="scope">
                                <el-image
                                    v-if="scope.row.imageUrl"
                                    style="width: 80px; height: 80px"
                                    :src="scope.row.imageUrl"
                                    :preview-src-list="[scope.row.imageUrl]"
                                    fit="contain"
                                ></el-image>
                                <span v-else>无</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="200">
                            <template #default="scope">
                                <el-button size="small" type="success" @click="openAuditDialog(scope.row, 'general')">批准</el-button>
                                <el-button size="small" type="danger" @click="auditCertification(scope.row.id, 2, 0, scope.row.applicantId)">拒绝</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                        @size-change="handleGeneralSizeChange"
                        @current-change="handleGeneralCurrentChange"
                        :current-page="generalCurrentPage"
                        :page-sizes="[10, 20, 50]"
                        :page-size="generalPageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="generalTotal"
                        background
                    >
                    </el-pagination>
                </el-tab-pane>

                <el-tab-pane label="课程认证" name="course">
                    <el-table :data="pendingCourseCertifications" style="width: 100%" v-loading="loadingCourse" border stripe>
                        <el-table-column prop="id" label="申请ID" width="180"></el-table-column>
                        <el-table-column prop="applicantUsername" label="申请人"></el-table-column>
                        <el-table-column prop="courseName" label="申请课程"></el-table-column>
                        <el-table-column prop="courseCredit" label="学分"></el-table-column>
                        <el-table-column label="证明图片" width="120">
                            <template #default="scope">
                                <el-image
                                    v-if="scope.row.imageUrl"
                                    style="width: 80px; height: 80px"
                                    :src="scope.row.imageUrl"
                                    :preview-src-list="[scope.row.imageUrl]"
                                    fit="contain"
                                ></el-image>
                                <span v-else>无</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="200">
                            <template #default="scope">
                                <el-button size="small" type="success" @click="auditCertification(scope.row.id, 1, scope.row.courseCredit, scope.row.applicantId)">批准</el-button>
                                <el-button size="small" type="danger" @click="auditCertification(scope.row.id, 2, 0, scope.row.applicantId)">拒绝</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                        @size-change="handleCourseSizeChange"
                        @current-change="handleCourseCurrentChange"
                        :current-page="courseCurrentPage"
                        :page-sizes="[10, 20, 50]"
                        :page-size="coursePageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="courseTotal"
                        background
                    >
                    </el-pagination>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <el-dialog
            v-model="auditDialogVisible"
            title="批准认证"
            width="400px"
            :close-on-click-modal="false"
        >
            <el-form :model="auditForm" label-width="80px">
                <el-form-item label="授予学分">
                    <el-input-number v-model="auditForm.credits" :min="0"></el-input-number>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="auditDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmAudit">确认批准</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { auditorService } from '../services/auditorService';
import { ElMessage, ElMessageBox } from 'element-plus';
// import { myRequest } from '@/utils/request'; // 导入 myRequest
import { userManager } from '@/utils/user'; // 导入 userManager
import { userServie } from '@/services/user_service';
export default {
    name: 'Auditor',
    components: {
        // Header, // 移除 Header 组件
    },
    data() {
        return {
            loginLoading: false, // 登录按钮加载状态
            loginForm: {
                password: ''
            },
            loginRules: {
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ]
            },
            isLoggedIn: false,
            activeTab: 'general', // 默认激活通用认证标签页

            // 通用认证列表数据
            pendingCertifications: [],
            generalTotal: 0,
            generalCurrentPage: 1,
            generalPageSize: 10,
            loadingGeneral: false,

            // 课程认证列表数据
            pendingCourseCertifications: [],
            courseTotal: 0,
            courseCurrentPage: 1,
            coursePageSize: 10,
            loadingCourse: false,

            // 审核对话框相关
            auditDialogVisible: false,
            auditForm: {
                certificationId: null,
                applicantId: null,
                credits: 0, // 默认学分
                auditType: null // 'general' 或 'course'
            }
        };
    },
    created() {
        // 在组件创建时，检查用户是否已经是审核员，如果是则直接显示面板
        // if (userManager.getUserInfo() && userManager.getUserType() === 2) { // 假设2代表审核员
        //     this.isLoggedIn = true;
        //     this.handleTabClick({ paneName: this.activeTab });
        // }
    },
    methods: {
        // 修改的函数: verifyPassword
        async verifyPassword() {
            this.$refs.loginFormRef.validate(async (valid) => {
                if (valid) {
                    this.loginLoading = true;
                    try {
                        const userId = userManager.getUserId(); // 获取当前登录用户的ID

                        if (!userId) {
                            ElMessage.error('无法获取用户ID，请先登录系统。');
                            this.loginLoading = false;
                            return;
                        }

                        // 【修改点】调用 userServie.activateAuditor，它返回一个 Promise
                        const res = await userServie.activateAuditor(this.loginForm.password);
                        
                        if (res && res.code === 1000) {
                            // 激活成功后，重新获取用户信息以更新本地存储的角色状态
                         // getMyInfo 接受回调，这里用空回调，因为await会等待Promise
                            const userInfoRes = await userServie.getMyInfoPromise(); 
                            console.log('获取用户信息结果:', userInfoRes);
                            if (userInfoRes && userInfoRes.code === 1000 && userInfoRes.data) {
                                // 更新本地的用户信息和角色
                                userManager.setUserInfo(userInfoRes.data.user, userInfoRes.data.student, userInfoRes.data.teacher);
                                if (userManager.getUserType() != 2) { // 确认更新后的类型是审核员
                                    this.isLoggedIn = true;
                                    ElMessage.success(res.msg || '审核员身份激活成功！');
                                    this.handleTabClick({ paneName: this.activeTab });
                                } else {
                                    ElMessage.error('身份激活成功但角色未更新，请联系管理员。');
                                }
                            } else {
                                ElMessage.error(userInfoRes?.msg || '获取用户最新信息失败。');
                            }

                        } else {
                            ElMessage.error(res?.msg || '激活失败，请重试。');
                        }
                    } catch (error) {
                        console.error('激活审核员身份请求异常:', error);
                        ElMessage.error('激活失败，请检查网络或稍后再试。');
                    } finally {
                        this.loginLoading = false;
                        this.loginForm.password = ''; // 清空密码输入
                    }
                }
            });
        },

        // 处理标签页切换
        handleTabClick(tab) {
            if (tab.paneName === 'general') {
                this.fetchPendingCertifications('general');
            } else if (tab.paneName === 'course') {
                this.fetchPendingCertifications('course');
            }
        },

        // 获取待审核列表的通用方法
        async fetchPendingCertifications(type) {
            // ... (此方法逻辑保持不变，因为后端已经正确处理过滤)
            if (type === 'general') {
                this.loadingGeneral = true;
                try {
                    const res = await auditorService.getPendingCertifications(this.generalCurrentPage, this.generalPageSize);
                    if (res.code === 1000 && res.data) {
                        this.pendingCertifications = res.data.records;
                        this.generalTotal = res.data.total;
                    } else {
                        ElMessage.error(res.msg || '获取通用认证列表失败。');
                    }
                } catch (error) {
                    console.error('获取通用认证列表出错:', error);
                    ElMessage.error('获取通用认证列表出错，请稍后再试。');
                } finally {
                    this.loadingGeneral = false;
                }
            } else if (type === 'course') {
                this.loadingCourse = true;
                try {
                    const res = await auditorService.getPendingCourseCertifications(this.courseCurrentPage, this.coursePageSize);
                    if (res.code === 1000 && res.data) {
                        this.pendingCourseCertifications = res.data.records;
                        this.courseTotal = res.data.total;
                    } else {
                        ElMessage.error(res.msg || '获取课程认证列表失败。');
                    }
                } catch (error) {
                    console.error('获取课程认证列表出错:', error);
                    ElMessage.error('获取课程认证列表出错，请稍后再试。');
                } finally {
                    this.loadingCourse = false;
                }
            }
        },

        // 通用认证分页
        handleGeneralSizeChange(val) {
            this.generalPageSize = val;
            this.fetchPendingCertifications('general');
        },
        handleGeneralCurrentChange(val) {
            this.generalCurrentPage = val;
            this.fetchPendingCertifications('general');
        },

        // 课程认证分页
        handleCourseSizeChange(val) {
            this.coursePageSize = val;
            this.fetchPendingCertifications('course');
        },
        handleCourseCurrentChange(val) {
            this.courseCurrentPage = val;
            this.fetchPendingCertifications('course');
        },

        // 打开批准对话框（仅通用认证需要输入学分）
        openAuditDialog(row, type) {
            this.auditForm.certificationId = row.id;
            this.auditForm.applicantId = row.applicantId;
            this.auditForm.auditType = type;
            // 如果是通用认证，学分需要手动输入；如果是课程认证，学分会从后端解析，此处不影响
            this.auditForm.credits = row.courseCredit !== undefined && row.courseCredit !== null ? row.courseCredit : 0;
            this.auditDialogVisible = true;
        },

        // 确认批准（通用认证）
        async confirmAudit() {
            // 通用认证的批准操作，将对话框中学分传递给后端
            await this.auditCertification(
                this.auditForm.certificationId,
                1, // 1表示批准
                this.auditForm.credits,
                this.auditForm.applicantId
            );
            this.auditDialogVisible = false; // 关闭对话框
        },

        // 执行学分认证批准/拒绝操作
        async auditCertification(certificationId, auditStatus, credits, applicantUserId) {
            // 对于拒绝操作，直接确认
            if (auditStatus === 2) {
                ElMessageBox.confirm('确定要拒绝此认证申请吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () => {
                    try {
                        // credits参数对于拒绝操作通常不重要，但API要求，可传0
                        const res = await auditorService.auditCertification(certificationId, auditStatus, credits, applicantUserId);
                        if (res.code === 1000) {
                            ElMessage.success(res.msg || '操作成功！');
                            this.refreshCurrentTab(); // 刷新当前标签页的数据
                        } else {
                            ElMessage.error(res.msg || '操作失败，请重试。');
                        }
                    } catch (error) {
                        console.error('学分认证操作失败:', error);
                        ElMessage.error('学分认证操作失败，请检查网络或稍后再试。');
                    }
                }).catch(() => {
                    ElMessage.info('已取消操作。');
                });
            } else {
                // 对于批准操作，通用认证会弹窗让输入学分，课程认证直接批准
                // 课程认证的批准按钮直接调用此方法，传入了 scope.row.courseCredit
                // 后端会根据是否是课程认证（解析description）来决定使用传入的credits还是解析的credits
                try {
                    const res = await auditorService.auditCertification(certificationId, auditStatus, credits, applicantUserId);
                    if (res.code === 1000) {
                        ElMessage.success(res.msg || '操作成功！');
                        this.refreshCurrentTab(); // 刷新当前标签页的数据
                    } else {
                        ElMessage.error(res.msg || '操作失败，请重试。');
                    }
                } catch (error) {
                    console.error('学分认证操作失败:', error);
                    ElMessage.error('学分认证操作失败，请检查网络或稍后再试。');
                }
            }
        },

        // 刷新当前激活标签页的数据
        refreshCurrentTab() {
            this.fetchPendingCertifications(this.activeTab);
        }
    },
    watch: {
        // 监听 isLoggedIn 状态，在登录成功后自动触发一次当前标签页的数据加载
        isLoggedIn(newVal) {
            if (newVal) {
                this.handleTabClick({ paneName: this.activeTab });
            }
        }
    }
};
</script>

 <style scoped>
 /* 移除 .common-layout 及其子容器的样式，因为它们导致了重复的顶栏和布局问题 */

 .auditor-page-container {
     padding: 20px;
     background-color: #f0f2f5; /* 页面背景色 */
     min-height: calc(100vh - 80px); /* 减去顶部Header的高度 */
     display: flex;
     justify-content: center; /* 使内容居中 */
     align-items: flex-start; /* 顶部对齐 */
 }

 .login-card {
     width: 100%;
     max-width: 400px; /* 控制登录卡片宽度 */
     margin-top: 50px; /* 顶部留白，避免紧贴Header */
     box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
     border-radius: 8px; /* 圆角 */
 }

 .auditor-panel {
     width: 100%;
     max-width: 1200px; /* 控制审核面板宽度 */
     margin-top: 30px;
     box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
     border-radius: 8px;
 }

 .card-header {
     display: flex;
     justify-content: center; /* 标题居中 */
     align-items: center;
     font-size: 20px;
     font-weight: bold;
     color: #303133;
     padding-bottom: 15px;
     border-bottom: 1px solid #ebeef5;
     margin-bottom: 20px;
 }

 .el-form-item {
     margin-bottom: 20px;
 }

 .login-button {
     width: 100%; /* 登录按钮宽度 */
 }

 .el-table {
     margin-top: 20px;
 }

 .el-pagination {
     margin-top: 20px;
     justify-content: flex-end;
 }

 .el-image {
     border-radius: 4px;
     overflow: hidden;
 }
 </style>